package com.algernoon.nettydemo.netty2.server;

import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class EchoServerHandler extends ChannelHandlerAdapter {

	private int counter;

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}

	/**
	 * 由于DelimiterBasedFrameDecoder自动对请求消息进行了解码，后续的ChannelHandler收到的msg对象就是个完整的消息包；
	 * 第二个ChannelHandler是StringDecoder将ByteBuf解码成字符串对象
	 * 第三个ChannelHandler即this 接收到的msg就是解码后的字符串
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		String body = (String) msg;
		System.out.println("request body is " + body +" , the counter is " + ++counter);
		// 由于设置DelimiterBasedFrameDecoder过滤掉了分隔符，所以返回给客户端时需要拼接分隔符“$_”
		body += "$_";
		ByteBuf echo = Unpooled.copiedBuffer(body.getBytes());
		ctx.writeAndFlush(echo);
	}
	
	public static void main(String[] args) {
		// 当前时间时间戳
		long currentTimeMillis = System.currentTimeMillis();
		// 当前时间加10分钟
		Date time = new Date(currentTimeMillis + 1000 * 60 * 10);
		System.out.println(time);
	}
	
}
